package com.gsit.job.flows;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.JDialog;
import javax.swing.JOptionPane;

import org.openqa.selenium.By;
import org.openqa.selenium.By.ById;
import org.openqa.selenium.By.ByLinkText;
import org.openqa.selenium.By.ByTagName;
import org.openqa.selenium.WebElement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.gsit.job.domain.SearchCriteria;
import com.gsit.job.domain.SearchStatus;
import com.gsit.job.services.PersonFileWriter;
import com.gsit.job.services.PersonService;
import com.gsit.job.services.SearchCriteriaService;
import com.gsit.job.services.UrlParser;


public abstract class SearchFlow extends FlowServiceAbs{
	
	@Autowired
	protected PersonFileWriter fileWriter;
	
	@Autowired
	protected UrlParser urlParser;
	
	@Autowired
	protected SearchCriteriaService searchCriteriaService;
	
	@Autowired
	protected PersonService personService;
	
	protected SearchCriteria searchCriteria;
	
	protected Integer currentPosition;
	
	
	protected void processTest(){
		List<SearchCriteria> criterias = searchCriteriaService.findAll();
		for (SearchCriteria searchCriteria : criterias) {
			System.out.println("criterias >>>>>>>>>>> "+searchCriteria);
		}
		
		SearchCriteria searchCriteria = searchCriteriaService.findSearchCriteriaByStatus(SearchStatus.NOT_STARTED);
		System.out.println("criterias >>>>>>>>>>> "+searchCriteria);
		
	}
	
	protected void process()throws Exception{
		loadSearchCriteria();
		processPages();
		finish();
	}
	
	
	
	protected void processPagesOnlyTest()throws Exception{
		doSearch();
		do{
			currentPosition++;
			processCurrentPage();
			updateSearchCriteria(SearchStatus.RUNNING);
			try{
				doNextClick();	
			}catch (Exception e) {
				processPagesOnlyTest();
			}
			
		}while(currentPosition < 2);
	}
	
	protected void processPages()throws Exception{
		doSearch();
		gotoPage();
		do{
			currentPosition++;
			processCurrentPage();
			updateSearchCriteria(SearchStatus.RUNNING);
			try{
				doNextClick();	
			}catch (Exception e) {
				doLoadWaitScreen();
				processPages();
			}
		}while(currentPosition < searchCriteria.getEndPosition());
	}
	
	private void gotoPage()throws Exception{
		if(currentPosition > 0){
			
			
			WebElement element = driver.findElement(By.id("txtPagetop"));
			if (element != null) {
				element.sendKeys(""+currentPosition);
			}
			List<WebElement> links=driver.findElements(By.tagName("a"));
			WebElement elementLink = null;
			for(WebElement mElementLink:links){
				String href = mElementLink.getAttribute("href");
				if(href!= null && href.toLowerCase().contains("javascript:goToPage(document.getElementById('txtPagetop').value);".toLowerCase())){
					elementLink = mElementLink;
					break;
				}
				
			}
			
			if(elementLink!=null){
				elementLink.click();
				sleep(5000);
			}else{
				throw new Exception("a WebElement is not found");
			}
			
			//goToPage_1
		}
	}
	
	protected void loadSearchCriteria()throws Exception{
		if(searchType!=null){
			
			searchCriteria = searchCriteriaService.findSearchCriteriaByStatusAndType(SearchStatus.RUNNING,searchType);
			if(searchCriteria == null){
				searchCriteria = searchCriteriaService.findSearchCriteriaByStatusAndType(SearchStatus.NOT_STARTED,searchType);
			}			
		}else{
			//searchCriteria = searchCriteriaService.findSearchCriteriaByStatus(SearchStatus.NOT_STARTED);
			//Assert.isNull(searchType);
			throw new Exception("No Search type found");
		}
		
		if(searchCriteria == null){
			//Assert.isNull(searchCriteria);
			throw new Exception("No SearchCriteria found");
		}else{
			currentPosition = searchCriteria.getCurrentPosition();
			updateSearchCriteria(SearchStatus.RUNNING);
		}
	}
	
	protected void updateSearchCriteria(SearchStatus searchStatus ){
		
		searchCriteria.setCurrentPosition(currentPosition);
		searchCriteria.setSearchStatus(searchStatus);
		if(searchCriteria.getSearchDate()==null){
			searchCriteria.setSearchDate(new Date());
		}		
		searchCriteriaService.saveOrUpdate(searchCriteria);
	}
	
	protected void finish(){
		updateSearchCriteria(SearchStatus.COMPLETED);
	}
	
	protected void doNextClick()throws Exception {
		WebElement nextElement = driver.findElement(ByLinkText.partialLinkText("Next"));
		if(nextElement != null ){
			applyDelyForPageLoad();
			nextElement.click();
		}else{
			System.out.println("No next Element found");
			throw new Exception("No next Element found");
		}
		
	}
	
	private void applyDelyForPageLoad(){
		if(currentPosition%100 ==0){
			System.out.println("Delay is called.");
			sleep(20000);
		}
	}
	
	private void doLoadWaitScreen(){
		System.out.println("Waiting for Captch Entry..................");
		try{
			WebElement element = driver.findElement(ById.id("jAlert"));
			if(element !=null){
				System.out.println("jAlert.isDisplayed :"+element.isDisplayed());
				if(!element.isDisplayed()){
					return;
				}
			}
		}catch (Exception e) {
			System.out.println("Exception while finding jAlert :");
			e.printStackTrace();
		}
		callWaitForCaptcha();
        currentPosition--;
        System.out.println("Moving for same round ..................");
        
	}
	
	protected abstract void doSearch()throws Exception;
	
	protected void processCurrentPage()throws Exception{
		//boolean isRightPage = false;
		//Long currentTime = new Date().getTime(); 
		List<String> urls = new ArrayList<String>();
		try{
			
			//List<WebElement> links=driver.findElements(By.tagName("a"));
			List<WebElement> links=driver.findElements(By.xpath("//a[@target='_blank']"));
			
			if(driver.getPageSource().contains("Please verify the code in pop-up")){
				doLoadWaitScreen();
				return;
			}else{
				for(WebElement ele:links){
					String href = ele.getAttribute("href");
					if(href!= null && href.contains("resume.html?resid")){
						urls.add(href);
						//isRightPage=true;
					}
				
				
				}
			}
			
			
			
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
		//System.out.println("Page proccing ...");
		//Long saveCurrentTime = new Date().getTime(); 
		personService.saveOrUpdate(urlParser.parse( urls));
		//System.out.println("Total time for Person save is >>>>>>>>>>>>>>>>>>>>>> "+(new Date().getTime() - saveCurrentTime));
		//System.out.println("Total time for Person creation is >>>>>>>>>>>>>>>>>>>>>> "+(new Date().getTime() - currentTime));
		
		
	}
}
